package com.jzo2o.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.DateUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.model.dto.request.ActivityQueryForPageReqDTO;
import com.jzo2o.market.model.dto.request.ActivitySaveReqDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {
    private static final int MILLION = 1000000;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ICouponService couponService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;

    /**
     * 新增活动
     *
     * @param activitySaveReqDTO
     */
    @Override
    public void saveOrUpdate(ActivitySaveReqDTO activitySaveReqDTO) {
        Integer type = activitySaveReqDTO.getType();
        if (type == null){
            throw new BadRequestException("优惠券类型不能为空");
        }else if (type == 1){
            BigDecimal discountAmount = activitySaveReqDTO.getDiscountAmount();
            if (discountAmount == null){
                throw new BadRequestException("满减优惠券的优惠金额不能为空");
            }
            if (discountAmount.compareTo(BigDecimal.ZERO) < 0){
                throw new BadRequestException("优惠金额请输入大于0的整数");
            }

        }else if (type == 2){
            Integer discountRate = activitySaveReqDTO.getDiscountRate();
            if (discountRate == null){
                throw new BadRequestException("折扣优惠券的折扣比例不能为空");
            }
            if (discountRate.compareTo(0) < 0 || discountRate.compareTo(100) > 0){
                throw new BadRequestException("折扣比例请输入大于0，小于10的整数");
            }
        }else {
            throw new BadRequestException("优惠券类型不存在");
        }
        LocalDateTime startTime = activitySaveReqDTO.getDistributeStartTime();
        LocalDateTime endTime = activitySaveReqDTO.getDistributeEndTime();
        if (startTime.isAfter(endTime) || startTime.isBefore(DateUtils.now())){
            throw new BadRequestException("发放时间不合法");
        }
        Activity activity = BeanUtils.toBean(activitySaveReqDTO, Activity.class);
        activity.setStatus(ActivityStatusEnum.NO_DISTRIBUTE.getStatus());
        activity.setStockNum(activity.getTotalNum());
        boolean save = this.saveOrUpdate(activity);
        if (!save){
            throw new DBException("新增或修改活动失败");
        }
    }


    /**
     * 分页查询活动
     *
     * @param dto
     * @return
     */
    @Override
    public Page<Activity> pageQuery(ActivityQueryForPageReqDTO dto) {
        Page<Activity> activityPage = PageUtils.parsePageQuery(dto, Activity.class);
        LambdaQueryWrapper<Activity> activityLambdaQueryWrapper = new LambdaQueryWrapper<Activity>()
                .eq(Activity::getIsDeleted, 0)
                .eq(ObjectUtils.isNotEmpty(dto.getId()), Activity::getId, dto.getId())
                .like(ObjectUtils.isNotEmpty(dto.getName()), Activity::getName, dto.getName())
                .eq(ObjectUtils.isNotEmpty(dto.getType()), Activity::getType, dto.getType())
                .eq(ObjectUtils.isNotEmpty(dto.getStatus()), Activity::getStatus, dto.getStatus())
                .orderByDesc(Activity::getCreateTime);
        Page<Activity> page = this.page(activityPage, activityLambdaQueryWrapper);
        return page;
    }

    /**
     * 撤销活动
     *
     * @param id
     */
    @Override
    public void revoke(Long id) {
        // 1.查询活动信息
        Activity activity = this.getById(id);
        if (activity == null){
            throw new BadRequestException("活动不存在");
        }
        Integer status = activity.getStatus();
        ArrayList<Integer> statuses = new ArrayList<>();
        statuses.add(ActivityStatusEnum.NO_DISTRIBUTE.getStatus());
        statuses.add(ActivityStatusEnum.DISTRIBUTING.getStatus());
        if (!statuses.contains(status)) {
            throw new BadRequestException("活动状态不合法");
        }
        activity.setStatus(ActivityStatusEnum.VOIDED.getStatus());
        boolean update = this.updateById(activity);
        if (!update){
            throw new DBException("撤销活动失败");
        }
        boolean updateStatus = couponService.lambdaUpdate().set(Coupon::getStatus, CouponStatusEnum.INVALID.getStatus())
                .eq(Coupon::getActivityId, activity.getId())
                .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus())
                .update();
        if (!updateStatus){
            throw new DBException("撤销活动失败");
        }
    }
}
